/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pfc.generacion;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ddlutils.model.Column;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import pfc.comun.IDEpfc;
import pfc.comun.Proyecto;
import pfc.modelocg.CGField;
import pfc.modelocg.CGForm;
import pfc.modelocg.CGModel;
import pfc.modelocg.CGModelIO;
import pfc.modeloer.ERAttrib;
import pfc.modeloer.EREntity;
import pfc.modeloer.ERModel;
import pfc.modeloer.ERReference;

/**
 *
 * @author xandru
 */
public class GeneradorWEB {

    Proyecto _proyecto;
    Database _dbmodel;
    ERModel _erModel;
    CGModel _cgModel;
    File webinf;
    private File classes;
    private File lib;
    private File conf;
    private File metainf;
    private File jsps;
    private File html;
    private File webpath;
    private File apppath;


    public GeneradorWEB(Proyecto pro, Database db, ERModel er, CGModel cg) {
        this._proyecto = pro;
        this._dbmodel = db;
        this._erModel = er;
        this._cgModel = cg;
    }

    public void generarWEB(File appPath) {
        this.apppath = appPath;
        File srcPath = new File(appPath + File.separator + "web");
        //    System.out.println("GenerandoWEB en " + srcPath);
        this.webpath = new File(appPath + File.separator + "web");
        webinf = new File(srcPath + File.separator + "WEB-INF");
        classes = new File(srcPath + File.separator + "WEB-INF" + File.separator + "classes");
        lib = new File(srcPath + File.separator + "WEB-INF" + File.separator + "lib");
        conf = new File(srcPath + File.separator + "WEB-INF" + File.separator + "conf");
        metainf = new File(srcPath + File.separator + "META-INF");
        jsps = new File(srcPath + File.separator + "jsp");
        html = new File(srcPath + File.separator + "html");


        try {
            FileUtils.forceMkdir(webinf);
            FileUtils.forceMkdir(classes);
            FileUtils.forceMkdir(lib);
            FileUtils.forceMkdir(conf);
            FileUtils.forceMkdir(metainf);
            FileUtils.forceMkdir(jsps);
            FileUtils.forceMkdir(html);


        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }

        generarWARDescriptor(webinf.getAbsolutePath() + File.separator + "web.xml");
        generarContextDescriptor(metainf.getAbsolutePath() + File.separator + "context.xml");
        generar();
    }

    private void generarWARDescriptor(String path) {
        IDEpfc.log("\n================Generando descriptor de despliegue =====================");
        IDEpfc.logTime("generado " + path);
        Document doc = null;
        String fichero = path;
        //  System.out.println("Generando war en " + path);
        try {

            doc = DocumentHelper.createDocument();

            Element root = doc.addElement("web-app");
            Element aux = root.addElement("description");
            aux.addText("Aplicacion del proyecto " + this._proyecto.nombre);

            for (EREntity ent : this._erModel.getEntityList()) {
                String servletName = "New" + StringUtils.capitalize(ent.getName());
                Element servlet = root.addElement("servlet");
                aux = servlet.addElement("servlet-name");
                aux.addText(servletName);
                aux = servlet.addElement("servlet-class");
                aux.addText(this._proyecto.nombre + ".servlet.New" + StringUtils.capitalize(ent.getName()));

                Element servletMapping = root.addElement("servlet-mapping");
                aux = servletMapping.addElement("servlet-name");
                aux.addText(servletName);
                aux = servletMapping.addElement("url-pattern");
                aux.addText("/servlet/" + "New" + StringUtils.capitalize(ent.getName()));


                servletName = "Update" + StringUtils.capitalize(ent.getName());
                servlet = root.addElement("servlet");
                aux = servlet.addElement("servlet-name");
                aux.addText(servletName);
                aux = servlet.addElement("servlet-class");
                aux.addText(this._proyecto.nombre + ".servlet.Update" + StringUtils.capitalize(ent.getName()));

                servletMapping = root.addElement("servlet-mapping");
                aux = servletMapping.addElement("servlet-name");
                aux.addText(servletName);
                aux = servletMapping.addElement("url-pattern");
                aux.addText("/servlet/" + "Update" + StringUtils.capitalize(ent.getName()));


                servletName = "Search" + StringUtils.capitalize(ent.getName());
                servlet = root.addElement("servlet");
                aux = servlet.addElement("servlet-name");
                aux.addText(servletName);
                aux = servlet.addElement("servlet-class");
                aux.addText(this._proyecto.nombre + ".servlet.Search" + StringUtils.capitalize(ent.getName()));

                servletMapping = root.addElement("servlet-mapping");
                aux = servletMapping.addElement("servlet-name");
                aux.addText(servletName);
                aux = servletMapping.addElement("url-pattern");
                aux.addText("/servlet/" + "Search" + StringUtils.capitalize(ent.getName()));

            }

            String servletName = "GetterServlet";
            Element servlet = root.addElement("servlet");
            aux = servlet.addElement("servlet-name");
            aux.addText(servletName);
            aux = servlet.addElement("servlet-class");
            aux.addText(this._proyecto.nombre + ".servlet.DBGetServlet");

            Element servletMapping = root.addElement("servlet-mapping");
            aux = servletMapping.addElement("servlet-name");
            aux.addText(servletName);
            aux = servletMapping.addElement("url-pattern");
            aux.addText("/servlet/" + "GetObject");


            Element resource = root.addElement("resource-ref");
            Element desc = resource.addElement("description");
            Element refName = resource.addElement("res-ref-name");
            refName.addText("jdbc/" + this._proyecto.getNombre());
            Element resType = resource.addElement("res-type");
            resType.addText("javax.sql.DataSource");
            Element resAuth = resource.addElement("res-auth");
            resAuth.addText("Container");

            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new FileWriter(fichero), format);
            writer.write(doc);
            writer.flush();

        } catch (Exception ex) {
            Logger.getLogger(CGModelIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void generar() {
        String fichero = webpath.getAbsolutePath() + File.separator + "index.html";
        String contexto = this._proyecto.nombre;
        PrintWriter index = null;
        try {
            //   System.out.println("Generando html en:" + fichero);
            index = new PrintWriter(new FileWriter(fichero));
            index.println("<html>");
            index.println("<head></head>");
            index.println("<body>");

            index.println("<table>");

            for (EREntity e : this._erModel.getEntityList()) {
                index.println("<tr>");
                index.println("<td>" + StringUtils.capitalize(e.getName()) + "</td>");
                index.println("<td>" + "<a href=/" + contexto + "/jsp/" + e.getName() + "EditForm.jsp" + "> Crear " + "</a></td>");
                index.println("<td>" + "<a href=/" + contexto + "/jsp/" + e.getName() + "SearchForm.jsp" + "> Buscar " + "</a></td>");

                index.println("</tr>");
            }

            index.println("</table>");
            index.println("</body>");
            index.println("</html>");


            index.flush();
            index.close();

        } catch (IOException ex) {
            Logger.getLogger(GeneradorWEB.class.getName()).log(Level.SEVERE, null, ex);
        }

        generarPaginas();

    }

    private void generarPaginas() {

        generateDBGetServlet();

        IDEpfc.log("\n================Generando Servlets =====================");

        for (CGForm form : this._cgModel.getForms()) {

            if (form.getType() == CGForm.FormType.EditForm) {
                generateEditForm(form);
                generateNewServlet(form);
                generateUpdateServlet(form);
                continue;
            }

            if (form.getType() == CGForm.FormType.SearchForm) {
                generateSearchForm(form);
                generateSearchServlet(form);
                continue;
            }

            if (form.getType() == CGForm.FormType.LinesForm) {
                generateLinesForm(form);
                continue;
            }
        }

    }

    private void generateEditForm(CGForm f) {

        String fichero = jsps.getAbsolutePath() + File.separator + f.getEntityName() + "EditForm.jsp";
        IDEpfc.logTime("generando " + fichero);
        int cols = f.getFields().size() > f.getNumberOfColumns() ? f.getNumberOfColumns() : f.getFields().size();
        EREntity ertable = f.getEntity();
        String className = StringUtils.capitalize(f.getEntityName());
        String classBO = className + "BO";

        //    System.out.println("Generando editForm gestion en:" + fichero);
        try {
            HTMLDocument doc = HTMLDocumentFactory.createDocument();
            doc.addJspImport(this._proyecto.nombre + "." + "dto.*");
            doc.addJspImport(this._proyecto.nombre + "." + "bo.*");
            doc.addJspImport("java.util.Properties");

            HTMLTag html = doc.getHTMLRoot();
            HTMLTag head = html.addHead();
            HTMLTag body = html.addBody();
            body.addJspCode("String contexto = request.getContextPath();");
            body.addJspCode("HttpSession ses = request.getSession(false);");
            body.addJspCode("String op = request.getParameter(\"op\");");
            body.addJspCode("String action=\"\";");
            body.addJspCode("String value = \"\";");
            body.addJspCode(className + " objeto=null;");
            body.addJspCode("if (op==null) action=contexto + \"/servlet/New" + StringUtils.capitalize(f.getEntityName()) + "\";");
            body.addJspCode("else {");
            body.addJspCode(" action=\"Update" + className + "\";");
            body.addJspCode(" objeto = (" + className + ")ses.getAttribute(\"objeto" + f.getEntityName() + "\");");
            body.addJspCode("}");
            body.addJspCode("");
            //HTMLTag form = body.addForm(f.getName(), "post", "<%=action%>");
            body.addText("<form name=\"" + f.getName() + "\" method=\"post\" action=<%=action%>>");
            //HTMLTag table = form.addTable();
            body.addText("<table>");
            //HTMLTag tr = table.addTableRow();
            body.addText("<tr>");
            //HTMLTag td = tr.addTableData();
            body.addText("<td>Editando " + f.getEntityName() + "</td></tr>");
            //td.addText("Editando " + f.getEntityName());


            for (CGField field : f.getFields()) {
                ERAttrib atr = field.getAttrib();
                Column col = atr.getColumn();


                if (!field.isPresent()) {
                    continue;
                }

                //tr = table.addTableRow();
                body.addText("<tr>");

                //td = tr.addTableData();
                body.addText("<td>" + field.getName() + "</td>");

                //td.addText(field.getName());

                //td = tr.addTableData();
                body.addText("<td>");

                body.addText("<%");
                body.addText("if (objeto!=null) {");
                body.addText(classBO + " boOjb =(" + classBO + ") BOFactory.getBO(\"" + classBO + "\");");
                body.addText("value = objeto.stringPropertyValue(\"" + field.getName() + "\");");
         //       body.addText("System.out.println(\"objeto." + field.getName() + "=\"  + objeto.stringPropertyValue(\"" + field.getName() + "\"));");
                body.addText("}");
                body.addText("%>");

                boolean crearinput = true;
                for (ERReference ref : this._erModel.getReferencedByAttrib(ertable, atr)) {
                    if (ref.getTargetEntity().getErElementType() == EREntity.EntityType.Master) {
                        String auxName = StringUtils.capitalize(ref.getTargetEntityName());
                        String auxBOName = auxName + "BO";

                        System.out.println(ref.getTargetEntityName() + " es una entidad maestra. generar select");
                        String auxobjName = "aux" + auxBOName;
                        body.addText("<%");
                        body.addText(auxBOName + " " + auxobjName + " = (" + auxBOName + ")BOFactory.getBO(\"" + auxBOName + "\");");
                        body.addText("%>");
                        body.addText("<select name=\"" + field.getName() + "\">");
                        body.addText("<%");
                        body.addText("for (" + auxName + " i:" + auxobjName + ".getAll()){");
                        body.addText("out.println(\"<option value=\" + i.getIdentity().getStringValue() + \">\" + i.stringDescription() + \"</option>\");");
                        body.addText("}");
                        body.addText("%>");
                        body.addText("</select>");
                    } else {
                        body.addText("<input type=\"text\" name=\"" + field.getName() + "\" value=\"<%=value%>\" readonly=\"true\" size=\"3\">");
                        //body.addText("<input type=\"text\" name=\"" + field.getName() + "String\" value=\"<%=value%>\" readonly=\"true\">");
                        String onclick = " onClick= \"window.open('" + ref.getTargetEntityName() + "SearchForm.jsp?op=select','" + ref.getTargetEntityName() + "','width=400,height=600,menubar=yes,location=yes,toolbar=yes')\"";
                        body.addText("<input type=\"button\" name=\"" + ref.getTargetEntityName() + "." + ref.getTargetAttribName() + "\" value=\"...\"" + onclick + ">");
                        String properties = "prop" + ref.getTargetEntityName();
                        String selec = "sel" + StringUtils.capitalize(ref.getTargetEntityName());
                        body.addText("<%Properties " + properties + " = new Properties();");
                        body.addText(properties + ".setProperty(\"paginaOrigen\",(request.getRequestURL()).toString());");
                        body.addText(properties + ".setProperty(\"formularioOrigen\",\"" + f.getName() + "\");");
                        body.addText(properties + ".setProperty(\"campoOrigen\",\"" + field.getName() + "\");");
                        body.addText(properties + ".setProperty(\"campoBuscado\",\"" + ref.getTargetAttribName() + "\");");
                        body.addText("ses.removeAttribute(\""+selec +"\");");
 //                body.addText("System.out.println(\"contexto de Busqueda en EditForm " + selec + "- " + properties + "\");");
                        body.addText("ses.setAttribute(\""+selec+"\"," + properties + ");%>");
                    }
                    crearinput = false;
                    continue;
                }


                if (crearinput) {
                    //HTMLTag input = td.addInput("text", field.getName(), "<%=value%>");
                    field.getAttrib().getSizeAsInt();


                    String texto = "<input type=\"text\" name=\"" + field.getName() + "\" value=\"<%=value%>\"";
                    //body.addText("<input type=\"text\" name=\"" + field.getName() + "\" value=\"<%=value%>\"");

                    if (field.getAttrib().getSizeAsInt()>0)
                        texto+= " maxlength=\"" + field.getAttrib().getSize() + "\"";

                    if ( (!field.isEditable())||(field.getAttrib().isGenerable())) {
                        //input.addAttribute("readonly", "true");
                        texto += " readonly=\"true\"";
                        //body.addText(" readonly=\"true\"");
                    }
                    body.addText(texto + ">");
                }
                body.addText("</td>");
                body.addText("</tr>");
            }
            //HTMLTag button = form.addInput("submit", "boton", "Grabar");
            body.addText("<tr><td><input type=\"submit\" name=\"boton\" value=\"Grabar\"></td></tr>");
            body.addText("</table>");
            body.addText("</form>");



            body.addText("<%out.println(contexto);%>");

            HTMLPrinter printer = new HTMLPrinter(fichero);
            printer.print(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void generateSearchForm(CGForm f) {
        String fichero = jsps.getAbsolutePath() + File.separator + f.getEntityName() + "SearchForm.jsp";
        IDEpfc.logTime("generando " + fichero);
        int cols = f.getFields().size() > f.getNumberOfColumns() ? f.getNumberOfColumns() : f.getFields().size();
        EREntity ertable = f.getEntity();

        //      System.out.println("Generando SearchForm en:" + fichero);
        try {
            HTMLDocument doc = HTMLDocumentFactory.createDocument();
            doc.addJspImport(this._proyecto.nombre + "." + "dto." + StringUtils.capitalize(f.getEntityName()));
            doc.addJspImport("org.apache.commons.lang.StringUtils");

            HTMLTag html = doc.getHTMLRoot();
            HTMLTag head = html.addHead();
            HTMLTag body = html.addBody();
            body.addJspCode("String contexto = request.getContextPath();");
            body.addJspCode("HttpSession ses = request.getSession(false);");
            body.addJspCode("String op = request.getParameter(\"op\");");
            body.addJspCode("String action=\"\";");
       //     body.addJspCode("System.out.println(\"op->\" + op);");
            body.addJspCode("if (StringUtils.isBlank(op)) {");
            body.addJspCode("action=contexto + \"/servlet/Search" + StringUtils.capitalize(f.getEntityName()) + "\";");
            body.addJspCode("op=\"edit\";");
            body.addJspCode("}");
            body.addJspCode("if (StringUtils.equals(op,\"update\")) action=\"update" + StringUtils.capitalize(f.getEntityName()) + "\";");
            body.addJspCode("if (StringUtils.equals(op,\"select\")) action=contexto + \"/servlet/Search" + StringUtils.capitalize(f.getEntityName()) + "\";");

            HTMLTag form = body.addForm(f.getName(), "post", "<%=action%>");
            HTMLTag table = form.addTable();
            HTMLTag tr = table.addTableRow();
            HTMLTag td = tr.addTableData();
            td.addText("Filtro de busqueda para " + f.getEntityName().toUpperCase());

            for (CGField field : f.getFields()) {
                ERAttrib atr = field.getAttrib();
                Column col = atr.getColumn();

                if ((!field.isSearcheable())||(!field.isVisible())) {
                    continue;
                }

                tr = table.addTableRow();
                td = tr.addTableData();
                td.addText(field.getName());
                td = tr.addTableData();

                boolean crearinput = true;
                for (ERReference ref : this._erModel.getReferencedByAttrib(ertable, atr)) {
                    //td = tr.addTableData();
                    HTMLTag tmp = td.addInput("text", field.getName(), "");
                    tmp.addAttribute("readonly", "true");

                    HTMLTag input = td.addInput("button", ref.getTargetEntityName() + "." + ref.getTargetAttribName(), "...");
                    crearinput = false;
                    continue;
                }

                if (crearinput) {
                    HTMLTag input = td.addInput("text", field.getName(), "");

                    if (!field.isEditable()) {
                        input.addAttribute("readonly", "true");
                    }
                }
            }
            HTMLTag op = form.addInput("hidden", "op", "<%=op%>");
            HTMLTag button = form.addInput("submit", "boton", "Buscar");



            body.addText("<%out.println(contexto);%>");

            body.addText("<a href=\"javascript:window.opener='x';window.close();\">Close</a>;");
            HTMLPrinter printer = new HTMLPrinter(fichero);
            printer.print(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void generateLinesForm(CGForm f) {
        String fichero = jsps.getAbsolutePath() + File.separator + f.getEntityName() + "LinesForm.jsp";
        IDEpfc.logTime("generando " + fichero);
        String formName = f.getEntityName() + "LinesForm";
        String capDTO = StringUtils.capitalize(f.getEntityName());
        String daoClassName = capDTO + "DAO";
        String entityName = f.getEntityName();

        try {
            HTMLDocument doc = HTMLDocumentFactory.createDocument();
            doc.addJspImport(this._proyecto.nombre + "." + "dto." + StringUtils.capitalize(f.getEntityName()));
            doc.addJspImport("java.util.List");
            doc.addJspImport("pfc.core.web.Pager");
            doc.addJspImport("java.util.Properties");

            HTMLTag html = doc.getHTMLRoot();
            HTMLTag head = html.addHead();
            HTMLTag body = html.addBody();
            body.addText("<script language=\"javascript\">");
            body.addText("function get_radio_value()");
            body.addText("{");
            body.addText("for (var i=0; i < document.lista" + capDTO + ".selection.length; i++)");
            body.addText("{");
            body.addText("if (document.lista" + capDTO + ".selection[i].checked)");
            body.addText("{");
            body.addText("var rad_val = document.lista" + capDTO + ".selection[i].value;");
            body.addText("}");
            body.addText("}");
           // body.addText("alert(document.lista" + capDTO + ".selection.length)");
           // body.addText("alert(rad_val);");
            body.addText("return rad_val;");
            body.addText("}");
            body.addText("</script>");

            body.addJspCode("String contexto = request.getContextPath();");
            body.addJspCode("String jspBase = contexto + \"/jsp/\";");
            body.addJspCode("HttpSession ses = request.getSession(false);");
            body.addJspCode("String op = request.getParameter(\"op\");");
            body.addJspCode("String pagina = request.getParameter(\"page\");");
            body.addJspCode("String attrName = \"lista" + capDTO + "\";");
            body.addJspCode("String pagerName = \"pager" + capDTO + "\";");
            body.addJspCode("String className = \"" + daoClassName + "\";");
            body.addJspCode("String entity = \"" + entityName + "\";");
            body.addJspCode("String contextoBusqueda = \"sel" + capDTO +"\";");
   //    body.addJspCode("System.out.println(\"contexto de busqueda -> \" + contextoBusqueda);");
            body.addJspCode("Properties busqueda = (Properties)ses.getAttribute(contextoBusqueda);");

            body.addJspCode("List<" + capDTO + "> lista = (List<" + capDTO + ">)ses.getAttribute(attrName);");
            body.addJspCode("Pager<" + capDTO + "> paginador = (Pager<" + capDTO + ">) ses.getAttribute(pagerName);");

           // body.addJspCode("System.out.println(\" op-> \" + op + \" busqueda->\" + busqueda);");
            //body.addJspCode("System.out.println(\"jsp ses=\" + ses + \" attrName=\" + attrName + \" " + capDTO + "\");");


            String submitCode = "document.lista" + capDTO + ".submit();";
            String valueCode = "get_radio_value();window.close()";
            
            String selectCode = "\"opener.document.\" + busqueda.getProperty(\"formularioOrigen\") + \".\" + busqueda.getProperty(\"campoOrigen\") + \".value=" + valueCode + "\"";
            //+"window.close();";
            body.addJspCode("String buttonValue = null;");
            body.addJspCode("String onclickCode=null;");
            body.addJspCode("if ((op!=null)&&(op.equals(\"select\"))) {");
            body.addJspCode("buttonValue=\"Seleccionar\";");
            body.addJspCode("onclickCode = " + selectCode + ";");
            body.addJspCode("}");
            body.addJspCode("if ((op!=null)&&(op.equals(\"edit\"))) {");
            body.addJspCode("buttonValue=\"Editar\";");
            body.addJspCode("onclickCode = \"" + submitCode + "\";");
            body.addJspCode("}");

            body.addText("<form name=\"lista" + capDTO + "\" action=\"<%=contexto%>/servlet/GetObject\" method=\"post\">");
            body.addText("<table border=1><tr><th colspan=" + f.getFields().size() + 1 + ">" + capDTO + "</th></tr>");

            body.addText("<tr><td>Sel.</td>");
            for (CGField field : f.getFields()) {
                if (!field.isVisible()) {
                    continue;
                }
                body.addText("<td>" + field.getName() + "</td>");
            }
            body.addText("</tr>");
            body.addText("<%for (" + capDTO + " obj: paginador.getPage(pagina)) {");
            body.addText("out.println(\"<tr>\");");
            body.addText("%><td><input type=\"radio\" name=\"selection\" value=\"<%=obj.getIdentity().getStringValue()%>\"/>");
            for (CGField field : f.getFields()) {
                if (!field.isVisible()) {
                    continue;
                }

                body.addText("<td><%=obj.get" + StringUtils.capitalize(field.getName()) + "()%></td>");
            }

            body.addText("</tr>");
            //body.addText("}");
            body.addText("<%}%>");
            
            /*
            body.addText("for (" + capDTO + " obj: lista) {");
            body.addText("out.println(\"<tr>\");");
            body.addText("%><td><input type=\"checkbox\" name=\"selection\" value=<%=obj.getIdentity()%>/>");
            for (CGField field : f.getFields()) {
            if (!field.isVisible()) {
            continue;
            }

            body.addText("<td><%=obj.get"+StringUtils.capitalize(field.getName())  +"()%></td>");
            }
            //body.addText("out.println(obj);");
            body.addText("</tr>");
            //body.addText("}");
            body.addText("<%}%>");
             */
            body.addText("</table>");
            body.addText("<input type=\"hidden\" name=\"op\" value=\"edit\"/>");
            body.addText("<input type=\"hidden\" name=\"entity\" value=\"<%=entity%>\"/>");


            body.addText("<input type=\"button\" value=\"<%=buttonValue%>\" onclick=\"<%=onclickCode%>\"/>");
            body.addText("</form>");


            body.addText("<table>");
            body.addText("<tr>");
            body.addText("<td><a href=\"<%=jspBase%>" + f.getEntityName() + "LinesForm.jsp?page=<%=paginador.getFirstPageNumber()%>&op=<%=op%>\">|<<|</a></td>");
            body.addText("<td><a href=\"<%=jspBase%>" + f.getEntityName() + "LinesForm.jsp?page=<%=paginador.getPreviousPageNumber()%>&op=<%=op%>\">|<|</a></td>");
            body.addText("<td>Pagina <%=paginador.getCurrentPageNumber()%> de <%=paginador.getLastPageNumber()%></td>");
            body.addText("<td><a href=\"<%=jspBase%>" + f.getEntityName() + "LinesForm.jsp?page=<%=paginador.getNextPageNumber()%>&op=<%=op%>\">|>|</a></td>");
            body.addText("<td><a href=\"<%=jspBase%>" + f.getEntityName() + "LinesForm.jsp?page=<%=paginador.getLastPageNumber()%>&op=<%=op%>\">|>>|</a></td>");
            body.addText("</tr></table>");

            HTMLPrinter printer = new HTMLPrinter(fichero);
            printer.print(doc);
        } catch (Exception e) {
        }
    }

    private void generarContextDescriptor(String path) {
        IDEpfc.log("\n=================Generando descriptor de contexto==================");
        IDEpfc.logTime("generado " + path);

        Document doc = null;
        String fichero = path;

        String dsFile = this._proyecto.getDSFilePath();

        if (dsFile == null) {
            dsFile = this._proyecto.getPath() + File.separator + "db" + File.separator + this._proyecto.getNombre() + "-ds.properties";
        }

        try {
            PropertiesConfiguration conf = null;
            conf = new PropertiesConfiguration(dsFile);

            doc = DocumentHelper.createDocument();
            Element root = doc.addElement("Context");
            Element resource = root.addElement("Resource");
            resource.addAttribute("auth", "Container");
            resource.addAttribute("driverClassName", (String) conf.getProperty("driver"));
            resource.addAttribute("maxActive", "100");
            resource.addAttribute("maxIdle", "30");
            resource.addAttribute("maxWait", "10000");
            resource.addAttribute("name", "jdbc/" + this._proyecto.getNombre());
            resource.addAttribute("password", (String) conf.getProperty("password"));
            resource.addAttribute("type", "javax.sql.DataSource");
            resource.addAttribute("url", (String) conf.getProperty("url"));
            resource.addAttribute("removeAbandoned", "true");
            resource.addAttribute("removeAbandonedTimeout", "30");
            resource.addAttribute("logAbandoned", "true");
            resource.addAttribute("username", (String) conf.getProperty("usuario"));




            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new FileWriter(fichero), format);
            writer.write(doc);
            writer.flush();

        } catch (Exception ex) {
            Logger.getLogger(CGModelIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void generateNewServlet(CGForm form) {
        File srcPath = new File(apppath + File.separator + this._proyecto.getSrcFolderName());
        File f = new File(srcPath + File.separator + "servlet");
        
        try {
            FileUtils.forceMkdir(f);

            GeneradorNewServlet gen = new GeneradorNewServlet(this._proyecto, this._dbmodel, this._erModel, this._cgModel);
            gen.generarServlet(f, form, "New");

        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void generateUpdateServlet(CGForm form) {
        File srcPath = new File(apppath + File.separator + this._proyecto.getSrcFolderName());
        File f = new File(srcPath + File.separator + "servlet");
        
        try {
            FileUtils.forceMkdir(f);

            GeneradorUpdateServlet gen = new GeneradorUpdateServlet(this._proyecto, this._dbmodel, this._erModel, this._cgModel);
            gen.generarServlet(f, form, "Update");

        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void generateSearchServlet(CGForm form) {

        File srcPath = new File(apppath + File.separator + this._proyecto.getSrcFolderName());
        File f = new File(srcPath + File.separator + "servlet");
        
        try {
            FileUtils.forceMkdir(f);

            GeneradorSearchServlet gen = new GeneradorSearchServlet(this._proyecto, this._dbmodel, this._erModel, this._cgModel);
            gen.generarServlet(f, form, "Search");

        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void generateDBGetServlet() {
        File srcPath = new File(apppath + File.separator + this._proyecto.getSrcFolderName());
        File f = new File(srcPath + File.separator + "servlet");
        String clase = "DBGetServlet";

        try {
            FileUtils.forceMkdir(f);
            String filePath = f.getAbsolutePath() + File.separator + clase + ".java";
            PrintWriter out = new PrintWriter(new FileOutputStream(filePath));
            out.println("package " + _proyecto.nombre + ".servlet;\n");

            out.println("import java.io.IOException;");
            out.println("import java.util.logging.Level;");
            out.println("import java.util.logging.Logger;");
            out.println("import javax.servlet.ServletException;");
            out.println("import javax.servlet.http.HttpServlet;");
            out.println("import javax.servlet.http.HttpServletRequest;");
            out.println("import javax.servlet.http.HttpServletResponse;");
            out.println("import javax.servlet.http.HttpSession;");
            out.println("import " + _proyecto.nombre + ".dao.*;");
            out.println("import " + _proyecto.nombre + ".dto.*;");
            out.println("import pfc.core.db.SinglePrimaryKey;");
            out.println("import pfc.core.db.DataSourceFactory;");
            out.println("import javax.sql.DataSource;");
            out.println("import org.apache.commons.lang.StringUtils;");


            out.println("public class " + clase + " extends HttpServlet {");
            out.println("protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {processRequest(request, response);}");
            out.println("protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {processRequest(request, response);}");
            out.println("protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{");
            out.println("String entity = request.getParameter(\"entity\");");
            out.println("String key = request.getParameter(\"selection\");");
            out.println("SinglePrimaryKey pk = new SinglePrimaryKey(key);");
            out.println("String classDAO = StringUtils.capitalize(entity) + \"DAO\";");
            out.println("try {");
            out.println("DataSource ds = DataSourceFactory.getDataSourceFromJNDI(\"jdbc/" + this._proyecto.getNombre() + "\");");
            out.println("BaseDAO dao = DAOFactory.newDAO(classDAO, ds);");
            out.println("BaseDTO dto = dao.findByPrimaryKey(pk);");
            out.println("System.out.println(\"obtenido un objeto de base de datos de tipo \" + dto.getClass().getCanonicalName());");

            out.println("HttpSession ses = request.getSession(false);");
            out.println("String attrName = \"objeto\" + entity ;");
            out.println("String url = \"/jsp/\" + entity + \"EditForm.jsp?op=edit\"; ");

            out.println("System.out.println(\"Atributo de sesion \" + attrName + \"=\" + dto);");
            out.println("ses.setAttribute(attrName, dto);");

            out.println("System.out.println(\"Redirigiendo a \" + url);");
            out.println("getServletConfig().getServletContext().getRequestDispatcher(url).forward(request,response);");





            out.println("} catch (Exception ex) {");
            out.println("Logger.getLogger(DBGetServlet.class.getName()).log(Level.SEVERE, null, ex);");
            out.println("}");

            out.println("}");
            out.println("}");

            out.flush();
            out.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
